#include "SystemTrayHelper.h"
#include <QSystemTrayIcon>
#include <QAction>
#include <QMenu>
#include <QDebug>
#include <QApplication>
#include <QTimer>
#include <QPainter>
#include <QPixmap>
#include <QPushButton>
#include <QHBoxLayout>

#include "../SystemMacro.h"

#ifdef _WIN32
#include "WinSystemTray.h"
#else
#include "../MacAppHelper.h"
#include "UnixSystemTray.h"
#endif

static QWidget *widget = nullptr;

#ifdef __APPLE__

#define OBJC_OLD_DISPATCH_PROTOTYPES 1

#include <objc/objc.h>
#include <objc/message.h>

void setupDockClickHandler();
bool dockClickHandler(id self,SEL _cmd,...);

#endif

#ifdef __APPLE__
void setupDockClickHandler() {
    Class cls = objc_getClass("NSApplication");
    objc_object *appInst = objc_msgSend((objc_object*)cls, sel_registerName("sharedApplication"));

    if(appInst != NULL) {
        objc_object* delegate = objc_msgSend(appInst, sel_registerName("delegate"));
        Class delClass = (Class)objc_msgSend(delegate,  sel_registerName("class"));
        SEL shouldHandle = sel_registerName("applicationShouldHandleReopen:hasVisibleWindows:");
        if (class_getInstanceMethod(delClass, shouldHandle)) {
            if (class_replaceMethod(delClass, shouldHandle, (IMP)dockClickHandler, "B@:"))
                qDebug() << "Registered dock click handler (replaced original method)";
            else
                qWarning() << "Failed to replace method for dock click handler";
        }
        else {
            if (class_addMethod(delClass, shouldHandle, (IMP)dockClickHandler,"B@:"))
                qDebug() << "Registered dock click handler";
            else
                qWarning() << "Failed to register dock click handler";
        }
    }
}

bool dockClickHandler(id self,SEL _cmd,...) {
    Q_UNUSED(self)
    Q_UNUSED(_cmd)

    // TODO 主界面展示

    // Return NO (false) to suppress the default OS X actions
    return false;
}
#endif

SystemTrayHelper &SystemTrayHelper::get()
{
    static SystemTrayHelper instance;
    return instance;
}

SystemTrayHelper::SystemTrayHelper()
{
#ifdef __APPLE__
    setupDockClickHandler();
#endif
}

void SystemTrayHelper::startFlash()
{
    if (m_systemTray)
        m_systemTray->startBlink();
}

void SystemTrayHelper::stopFlash()
{
    if (m_systemTray)
        m_systemTray->stopBink();
}

QIcon SystemTrayHelper::getIconWithNum(int num)
{
    QPixmap map(32,32);
    //    map.fill(Qt::transparent);
    //    QPainter p(&map);
    //    p.drawPixmap(0,0,32,32,QPixmap("/Users/sl/remind_QQlogo_normal@2x.png"));
    //    p.setPen(Qt::black);
    //    p.setBrush(Qt::black);
    //    QFont font = qApp->font();
    //    font.setPointSize(25);
    //    p.setFont(font);

    //    p.drawText(QRect(32,0,32,32),Qt::AlignCenter,QString::number(num));
    //    p.end();
    //    map.save("/Users/sl/hehe.png");
    return QIcon(map);
}

void SystemTrayHelper::installSystemTray(QWidget *parent)
{
    qDebug() << "install system tray";
    QMenu *menu = new QMenu();
    QAction *actionShow = new QAction(tr("Open") + tr("APP"),menu);

    menu->addSeparator();

    QAction *actionQuit = new QAction(tr("Quit"),menu);

    menu->addAction(actionShow);
    menu->addSeparator();
    menu->addAction(actionQuit);

    connect(actionShow,&QAction::triggered,[parent](){
        // TODO 主界面展示
    });

    connect(actionQuit,&QAction::triggered,[parent]() {
        qApp->quit();
    });

    m_parent = parent;
    widget = parent;

#ifdef _WIN32
    m_systemTray = new WinSystemTray(QIcon(":/Resource/images/app.ico"),0);
#endif

#ifdef __APPLE__
    if (MacAppHelper::isDarkMode())
        m_systemTray = new UnixSystemTray(QIcon(":/Resource/images/app_mac_dark.png"),parent);
    else
        m_systemTray = new UnixSystemTray(QIcon(":/Resource/images/app_mac.png"),parent);
#endif

#ifdef __linux__
    m_systemTray = new UnixSystemTray(QIcon(":/Resource/images/app.ico"),0);
#endif

    connect(m_systemTray,&SystemTrayInterface::activated,[this,parent,menu](QSystemTrayIcon::ActivationReason reason){
        switch (reason) {
        case QSystemTrayIcon::DoubleClick:
        case QSystemTrayIcon::Trigger:
        {
            qDebug() << "Trigger";
            break;
        }
        default:
            qDebug() << "reason" << reason;
            break;
        }
    });

#if defined(_WIN32) || defined(__linux__)
//    connect(m_systemTray,&SystemTrayInterface::enter,SHMWebTrayView::get(),&SHMWebTrayView::onEnter);
//    connect(m_systemTray,&SystemTrayInterface::leave,SHMWebTrayView::get(),&SHMWebTrayView::onLeave);
    // TODO 响应托盘移入和移出事件
    m_systemTray->setContextMenu(menu);
#endif

    m_systemTray->setVisible(true);
}
